<?php
namespace app\services\tools;

use EasyWeChat\Factory;
use app\helper\tools\EasyWechatCache;
use EasyWeChat\Kernel\Messages\Text;
use Symfony\Component\Cache\Simple\RedisCache;
use \EasyWeChat\OfficialAccount\Application;

class WechatService
{
    protected static $_instance;
    protected $wx;

    /**
     * WechatService constructor.
     * @param Application $wechat
     */
    public function __construct(Application $wechat)
    {
        $this->wx = $wechat;
    }

    /**
     * 构建wechat 并使用redis缓存
     * @param array $config
     * @return mixed
     */
    public static function getInstance($config = [])
    {
        if (empty(self::$_instance)) {
            $config = array_merge(config('wechat.default'), $config);
            $wechat = Factory::officialAccount($config);

            /**
             * 更改easywechat 缓存驱动，
             * 由于thinkphp的Cache::handler返的对象有问题，配置的选项不生效
             * 所以自定义new \Predis\Client来处理
             */
            if (config('cache.type') == 'redis') {
                $redis = new EasyWechatCache();
                $cache = new RedisCache($redis->getHandler());
                $wechat['cache'] = $cache;
            }
            self::$_instance = new self($wechat);
        }
        return self::$_instance;
    }

    public function getWechat()
    {
        return $this->wx;
    }

    public function sendText($openid, $text)
    {
        return $this->wx->customer_service
            ->message(new Text($text))
            ->to($openid)
            ->send();
    }
}
